package com.lucfzy.controller;

import com.lucfzy.employee.EmployeeMapper;
import com.lucfzy.jwt.UserInfo;
import com.lucfzy.resp.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    private EmployeeMapper employeeMapper;

    @PostMapping("/register")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Response registerUserInfo(@RequestBody UserInfo userInfo) {
        try {
            String inputUsername = userInfo.getUsername();
            if (StringUtils.isEmpty(inputUsername)){
                throw new RuntimeException("username can not be null!");
            }
            int count = employeeMapper.findByUserName(inputUsername);
            if (count > 0) {
                throw new RuntimeException("该用户名已被注册，请重新注册！！");
            }
            employeeMapper.insert(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.error(e.getMessage());
        }
        return Response.ok();
    }

    @PostMapping("/updatePass")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Response updateUserPass(@RequestBody UserInfo userInfo) {
        try {
            String inputUsername = userInfo.getUsername();
            if (StringUtils.isEmpty(inputUsername)){
                throw new RuntimeException("username can not be null!");
            }
            int count = employeeMapper.findByUserName(inputUsername);
            if (count == 0) {
                throw new RuntimeException("该用户名不存在，请重新输入！！");
            }
            employeeMapper.updatePass(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.error(e.getMessage());
        }
        return Response.ok();
    }

}
